package com.ys.service.business.impl;

import com.alibaba.fastjson.JSON;
import com.ys.entity.amazonorder.TcoDayShop;
import com.ys.entity.amazonorder.TcoMonthShop;
import com.ys.entity.business.TpAmazonShop;
import com.ys.entity.business.TpAnalysisDailyTargetSet;
import com.ys.entity.hr.ThrOperateCompanyApply;
import com.ys.entity.sys.YsDict;
import com.ys.mapper.business.DiySqlMapper;
import com.ys.mapper.business.TpAnalysisDailyTargetSetMapper;
import com.ys.service.business.TpAnalysisDailyTargetSetService;
import com.ys.util.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.function.Predicate;
import java.util.stream.Collectors;

@Service("tpAnalysisDailyTargetSetService")
public class TpAnalysisDailyTargetSetServiceImpl implements TpAnalysisDailyTargetSetService {

	@Autowired
	private TpAnalysisDailyTargetSetMapper tpAnalysisDailyTargetSetMapper;

	@Autowired
	private DiySqlMapper diySqlMapper;

	/**
	 * 新增当月数据，更新当月日目标
	 * @return
	 */
	@Override
	public int addThisMonth(String thisMonth) {

		//获取这个月时间
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
		Calendar calendar = Calendar.getInstance();

		Date thisMonthDate = null;
		try {
			thisMonthDate = sdf.parse(thisMonth);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		calendar.setTime(thisMonthDate);
		calendar.add(Calendar.MONTH, -1);
		String oldMonth = sdf.format(calendar.getTime());//上个月

		//获取所有运营公司数据
		List<ThrOperateCompanyApply> companyList = new ThrOperateCompanyApply().queryList();
		if(companyList!=null && companyList.size()>0){

			//获取达成目标系数、未达成目标系数
			List<YsDict> coefficientList = new YsDict().where("A.DictKey ='TP_AnalysisDailyTarget_Coefficient'").queryList();
			//查询是否有上个月的设置数据
			List<TpAnalysisDailyTargetSet> oldMonthTargeList = new TpAnalysisDailyTargetSet().where("A.InfoTime = '"+oldMonth+"'").queryList();
			//查询是否有这个月的设置数据
			List<TpAnalysisDailyTargetSet> thisMonthTargeList = new TpAnalysisDailyTargetSet().where("A.InfoTime = '"+thisMonth+"'").queryList();

			//循环处理数据，并新增
			companyList.forEach(companyItem->{
				String VgsBm = companyItem.getVgsbm();
				TpAnalysisDailyTargetSet entity = new TpAnalysisDailyTargetSet();
				entity.setInfoTime(thisMonth);
				entity.setStatus(1);
				entity.setVGsBm(VgsBm);

				int dailyTarget = 3;//默认日目标
				int elaborateDailyTarget = 3;//默认精品日目标

				if(oldMonthTargeList!=null && oldMonthTargeList.size()>0){
					//根据运营公司编码过滤
					List<TpAnalysisDailyTargetSet> oldMonthTargeListByShop = oldMonthTargeList.stream()
							.filter(item->item.getVGsBm().equals(VgsBm))
							.collect(Collectors.toList());
					if(coefficientList!=null && coefficientList.size()>0 && oldMonthTargeListByShop.size()>0){
						BigDecimal coefficientX =  new BigDecimal("0");//达成目标系数
						BigDecimal coefficientY =  new BigDecimal("0");//未达成目标系数
						BigDecimal coefficientElaborateX =  new BigDecimal("0");//精品达成目标系数
						BigDecimal coefficientElaborateY =  new BigDecimal("0");//精品未达成目标系数
						for(YsDict dictItem: coefficientList){
							if(dictItem.getDictName().equals("达成目标系数")){
								coefficientX =  new BigDecimal(dictItem.getDictValue());
							}else if(dictItem.getDictName().equals("未达成目标系数")){
								coefficientY =  new BigDecimal(dictItem.getDictValue());
							}else if(dictItem.getDictName().equals("精品达成目标系数")){
								coefficientElaborateX =  new BigDecimal(dictItem.getDictValue());
							}else {
								coefficientElaborateY =  new BigDecimal(dictItem.getDictValue());
							}
						}
						BigDecimal oneNum = new BigDecimal("1");
						//根据规则计算：日目标=上月的日均目标+X*上月的目标达成率（达成），X：达成目标系数，≥100%时，整数。
						//日目标==上月的日均目标+Y*（1+（1-上月的目标达成率））（未达成）,Y：未达成目标系数，<100%时，整数。
						//subtract
						BigDecimal oldMonthGrowthRate = oldMonthTargeListByShop.get(0).getGrowthRate();//上月的目标达成率
						BigDecimal oldMonthElaborateGrowthRate = oldMonthTargeListByShop.get(0).getElaborateGrowthRate();//上月的目标达成率->精品
						BigDecimal oldMonthDailyTarget = new BigDecimal(oldMonthTargeListByShop.get(0).getDailyTarget());//上个月的日目标
						BigDecimal oldMonthElaborateDailyTarget = new BigDecimal(oldMonthTargeListByShop.get(0).getElaborateDailyTarget());//上个月的精品日目标
						//计算日目标
						if(oldMonthGrowthRate.compareTo(BigDecimal.ZERO)>0){
							if(oldMonthGrowthRate.compareTo(oneNum)>=0){//上月的目标达成率为正
								dailyTarget = oldMonthDailyTarget.add(coefficientX.multiply(oldMonthGrowthRate)).intValue();
							}else {
								dailyTarget = oldMonthDailyTarget.add(coefficientY.multiply(oneNum.add(oneNum.subtract(oldMonthGrowthRate)))).intValue();
							}
						}
						//计算日目标_精品
						if(oldMonthElaborateGrowthRate.compareTo(BigDecimal.ZERO)>0){
							if(oldMonthElaborateGrowthRate.compareTo(oneNum)>=0){//上月的目标达成率为正
								elaborateDailyTarget = oldMonthElaborateDailyTarget.add(coefficientElaborateX.multiply(oldMonthElaborateGrowthRate)).intValue();
							}else {
								elaborateDailyTarget = oldMonthElaborateDailyTarget.add(coefficientElaborateY.multiply(oneNum.add(oneNum.subtract(oldMonthElaborateGrowthRate)))).intValue();
							}
						}

					}
				}
				//保底为3
				if(dailyTarget<3){
					dailyTarget = 3;
				}
				if(elaborateDailyTarget<3){
					elaborateDailyTarget = 3;
				}
				//填入目标
				entity.setDailyTarget(dailyTarget);
				entity.setElaborateDailyTarget(elaborateDailyTarget);
				List<TpAnalysisDailyTargetSet> thisList = thisMonthTargeList.stream()
						.filter(item->item.getVGsBm().equals(VgsBm))
						.collect(Collectors.toList());
				if(thisList.size()>0){
					//修改
					entity.setId(thisList.get(0).getId());
					tpAnalysisDailyTargetSetMapper.update(entity);
				}else {
					//新增
					tpAnalysisDailyTargetSetMapper.insert(entity);
				}

			});
		}
		return 1;
	}


	/**
	 * 更新上个月的增长率
	 * @return
	 */
	@Override
	public int editOldMonthData(String oldMonth) {

		int lastDay = new DateUtil().getMonthLastDay(oldMonth);//获取月份的最后一天

		Predicate<List> listIsNull = listInfo-> listInfo!=null && listInfo.size()>0;

		//查询上个月的设置数据
		List<TpAnalysisDailyTargetSet> oldMonthTargeList = new TpAnalysisDailyTargetSet().where("A.InfoTime = '"+oldMonth+"'").queryList();

		if(listIsNull.test(oldMonthTargeList)){
			//统计查询上个月和上上个月的商品订单数据
			List<Map<String, Object>> oldMonthOrderList = diySqlMapper.searchOldMonthAllOrderList(oldMonth+"-01",oldMonth+"-"+lastDay);
			//统计查询上个月和上上个月的精品订单数据
			List<Map<String, Object>> oldMonthElaborateOrderList = diySqlMapper.searchOldMonthElaborateOrderList(oldMonth+"-01",oldMonth+"-"+lastDay);

			//循环处理数据，并修改
			oldMonthTargeList.forEach(setItem->{
				String VgsBm = setItem.getVGsBm();
				TpAnalysisDailyTargetSet entity = new TpAnalysisDailyTargetSet();
				entity.setId(setItem.getId());
				entity.setStatus(1);
				int dailyTarget = setItem.getDailyTarget();//上个月日目标
				int elaborateDailyTarget = setItem.getElaborateDailyTarget();//上个月日目标-精品

				BigDecimal growthRate =  new BigDecimal("0");//月增长率
				BigDecimal elaborateGrowthRate =  new BigDecimal("0");//精品月增长率

				if(listIsNull.test(oldMonthOrderList)){
					//根据shopGuid过滤上个月的商品订单统计数据
					List<Map<String, Object>> oldMonthOrderByShop = oldMonthOrderList.stream()
							.filter(item->item.get("VGsBm")!=null && item.get("VGsBm").toString().equals(VgsBm))
							.collect(Collectors.toList());
					if(oldMonthOrderByShop.size()>0){
						entity.setOrderTotal(Integer.parseInt(oldMonthOrderByShop.get(0).get("Num").toString()));
						//获取月目标总数
						BigDecimal monthTotal = new BigDecimal(lastDay).multiply(new BigDecimal(dailyTarget));//月天数*日目标
						//计算达成率
						BigDecimal oldData = new BigDecimal(oldMonthOrderByShop.get(0).get("Num").toString());
						growthRate =  (BigDecimal.ZERO).compareTo(monthTotal) == 0 ? new BigDecimal("1"):oldData.divide(monthTotal,4,BigDecimal.ROUND_HALF_UP);
					}

				}

				if(listIsNull.test(oldMonthElaborateOrderList)){
					//根据shopGuid过滤上个月的精品订单统计数据
					List<Map<String, Object>> oldMonthElaborateOrderListByShop = oldMonthElaborateOrderList.stream()
							.filter(item->item.get("VGsBm")!=null &&item.get("VGsBm").toString().equals(VgsBm))
							.collect(Collectors.toList());
					if(oldMonthElaborateOrderListByShop.size()>0){
						entity.setElaborateOrderTotal(Integer.parseInt(oldMonthElaborateOrderListByShop.get(0).get("Num").toString()));
						//获取月目标总数
						BigDecimal monthTotal = new BigDecimal(lastDay).multiply(new BigDecimal(elaborateDailyTarget));//月天数*日目标
						//计算达成率
						BigDecimal oldData = new BigDecimal(oldMonthElaborateOrderListByShop.get(0).get("Num").toString());
						elaborateGrowthRate =  (BigDecimal.ZERO).compareTo(monthTotal) == 0 ? new BigDecimal("1"):oldData.divide(monthTotal,4,BigDecimal.ROUND_HALF_UP);

					}
				}
				entity.setGrowthRate(growthRate);
				entity.setElaborateGrowthRate(elaborateGrowthRate);
				//修改
				tpAnalysisDailyTargetSetMapper.update(entity);
			});
		}
		return 1;
	}

	@Override
	public List<Map<String, Object>> searchOldMonthAllOrderList(String startTime,String endTime){
		return diySqlMapper.searchOldMonthAllOrderList(startTime,endTime);
	}

	@Override
	public List<Map<String, Object>> searchOldMonthElaborateOrderList(String startTime,String endTime){
		return diySqlMapper.searchOldMonthElaborateOrderList(startTime,endTime);
	}

	@Override
	public int updateYsDictByAnalysisDailyTargetCoefficient(String dictName,String dictValue){
		return diySqlMapper.updateYsDictByAnalysisDailyTargetCoefficient(dictName,dictValue);
	}

	@Override
	public int editDailyTarget(Map<String, Object> params){
		//修改
		TpAnalysisDailyTargetSet entity = JSON.parseObject(JSON.toJSONString(params), TpAnalysisDailyTargetSet.class);
		entity.setStatus(1);
		return tpAnalysisDailyTargetSetMapper.update(entity);
	}


	/**
	 * 新增当月数据，更新当月日目标
	 * @return
	 */
	@Override
	public int addThisMonthByDiy(String startTime,String endTime,int dayNum) {

		BigDecimal dayNumBig = new BigDecimal(dayNum);
		//获取这个月时间
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
		Calendar calendar = Calendar.getInstance();
		String thisMonth = sdf.format(calendar.getTime());//这个月
		calendar.add(Calendar.MONTH, -1);
		String oldMonth = sdf.format(calendar.getTime());//上个月

		//获取所有运营公司数据
		List<ThrOperateCompanyApply> companyList = new ThrOperateCompanyApply().queryList();
		if(companyList!=null && companyList.size()>0){

			//查询是否有这个月的设置数据
			List<TpAnalysisDailyTargetSet> thisMonthTargeList = new TpAnalysisDailyTargetSet().where("A.InfoTime = '"+thisMonth+"'").queryList();

			//统计查询昨天的月份的累计商品订单数据
			List<Map<String, Object>> oldDayOrderTotal = diySqlMapper.searchOldMonthAllOrderList(startTime,endTime);
			//统计查询昨天的月份的累计精品订单数据
			List<Map<String, Object>> oldDayElaborateOrderTotal = diySqlMapper.searchOldMonthElaborateOrderList(startTime,endTime);


			//循环处理数据，并新增
			companyList.forEach(companyItem->{
				String VgsBm = companyItem.getVgsbm();
				TpAnalysisDailyTargetSet entity = new TpAnalysisDailyTargetSet();
				entity.setInfoTime("2023-08");
				entity.setStatus(1);
				//entity.setShopGuid(shopGuid);

				List<Map<String, Object>> oldDayOrderTotalByShop =oldDayOrderTotal.stream()
						.filter(item->item.get("VgsBm").equals(VgsBm)).collect(Collectors.toList());
				List<Map<String, Object>> oldDayElaborateOrderTotalByShop =oldDayElaborateOrderTotal.stream()
						.filter(item->item.get("VgsBm").toString().equals(VgsBm)).collect(Collectors.toList());

				int dailyTarget = 0;//默认日目标
				int elaborateDailyTarget = 0;//默认精品日目标
				if(oldDayOrderTotalByShop.size()>0){
					dailyTarget = new BigDecimal(oldDayOrderTotalByShop.get(0).get("Num").toString()).divide(dayNumBig,4,BigDecimal.ROUND_HALF_UP).intValue();
				}
				if(oldDayElaborateOrderTotalByShop.size()>0){
					elaborateDailyTarget = new BigDecimal(oldDayElaborateOrderTotalByShop.get(0).get("Num").toString()).divide(dayNumBig,4,BigDecimal.ROUND_HALF_UP).intValue();
				}

				//填入目标
				entity.setDailyTarget(dailyTarget);
				entity.setElaborateDailyTarget(elaborateDailyTarget);
				List<TpAnalysisDailyTargetSet> thisList = thisMonthTargeList.stream()
						.filter(item->item.getVGsBm().equals(VgsBm))
						.collect(Collectors.toList());
				if(thisList.size()>0){
					//修改
					entity.setId(thisList.get(0).getId());
					tpAnalysisDailyTargetSetMapper.update(entity);
				}else {
					//新增
					tpAnalysisDailyTargetSetMapper.insert(entity);
				}

			});
		}
		return 1;
	}

}
